package de.wtschreiter.structured.document.io.event.basic;

import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.*;

import de.wtschreiter.structured.document.io.event.*;

public abstract class AbstractBasicAttributedEvent extends AbstractBasicEvent implements AttributedEvent {

    private final Map<String, String> attributes = new HashMap<String, String>();

    public AbstractBasicAttributedEvent(final EventType type) {
        super(type);
    }

    @Override
    public String getAttribute(final String key) {
        return StringUtils.defaultIfEmpty(attributes.get(key), EventConstance.EMPTY_ATTRIBUTE_VALUE);
    }

    @Override
    public Collection<String> getAttributeKeys() {
        return new ArrayList<>(attributes.keySet());
    }

    public void setAttributes(final Map<String, String> attributes) {
        this.attributes.putAll(attributes);
    }

    protected boolean hasSameAttribures(final AttributedEvent other) {
        final EqualsBuilder equalsBuilder = new EqualsBuilder();
        equalsBuilder.append(attributes.keySet(), other.getAttributeKeys());
        for (final String attributeKey : attributes.keySet()) {
            equalsBuilder.append(attributes.get(attributeKey), other.getAttribute(attributeKey));
        }
        return equalsBuilder.isEquals();
    }

    protected ToStringBuilder appendAttributes(final ToStringBuilder toStringBuilder) {
        return toStringBuilder.append("attributes", attributes);
    }

    @Override
    public int hashCode() {
        return attributes.hashCode();
    }

}
